package com.atguigu.gmall.realtime.util;

import com.atguigu.gmall.realtime.bean.User;
import com.atguigu.gmall.realtime.common.Constant;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/25 11:48
 */
public class JdbcUtil {
    
    // 获取Phoenix连接对象
    public static Connection getPhoenixConnection(String url) {
        String driver = Constant.PHOENIX_DRIVER;
        return getJdbcConnection(driver, url);
    }
    
    public static Connection getMysqlConnection(String url) {
        String driver = Constant.MYSQL_DRIVER;
        return getJdbcConnection(driver, url);
    }
    
    public static Connection getJdbcConnection(String driver, String url) {
        try {
            Class.forName(driver);// jdbc:mysql
            return DriverManager.getConnection(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
  
    
    public static void main(String[] args) {
        List<User> list = JdbcUtil.queryList(getMysqlConnection("jdbc:mysql://hadoop162:3306/gmall2021?user=root&password=aaaaaa"),
                                             "select * from spu_info",
                                             new Object[]{},
                                             User.class);
        for (User object : list) {
            System.out.println(object);
        }
    }
    
    // 通过标准的jdbc 去表中查询数据
    // ? , ?, ?
    public static <T> List<T> queryList(Connection conn, String sql, Object[] args, Class<T> tClass) {
        ArrayList<T> result = new ArrayList<>();
    
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            // 给占位符赋值
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
    
            ResultSet resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            // 一共多少列? 通过resultSet 来获取
            while (resultSet.next()) { // while进来一次, 就表示已经拿到了一行数据
                T t = tClass.newInstance();
                for (int i = 1; i <= columnCount; i++) { // 遍历这一行所有的列
                    String columnName = metaData.getColumnLabel(i);
                    Object value = resultSet.getObject(columnName);
                    BeanUtils.setProperty(t, columnName, value);
                }
                result.add(t);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return result;
    }
}
